
var	count = 2;
var z = [1];

var Contact = {
	_cc_option : {
		rules: {
			tel: {
				tel: true
			},
			fax: {
				tel: true
			},
			mobile: {
				mobile: true
			},
			email: {
				email: true
			}			
		},
		errorPlacement: function(label, element) {
			label.insertAfter(element);
		},
		success: function(label) {
			label.html("&nbsp;").addClass("checked");
		}
	},
	
	validate_add: function() {
		if (!validator.form()) {
			return false;
		}
	
		var cc;
		for (var i = 0; i < z.length; i++) {
			cc = $("#form" + z[i]).validate(this._cc_option);	
			if (!cc.form()) {
				return false;
			}
		}
		
		return true;	
	},
	
	add: function () {
		z.push(count);

		var contact = $("#contact" + z[0]).clone();
		contact.attr("id", "contact" + count);

		$("#action" + z[0]).attr("id", "action_");
		$("#form" + z[0]).attr("id", "form_");

		contact.insertBefore("#contact_new");

		$("#action" + z[0]).attr("id", "action" + count);
		$("#form" + z[0]).attr("id", "form" + count);

		$("#action_").attr("id", "action" + z[0]);
		$("#form_").attr("id", "form" + z[0]);

		$("#contact" + count + " :input").val("");

		count++;

		this.refresh();
	},

	remove: function (k) {
		$("#contact" + k).remove();

		for (var i = 0; i < z.length; i++) {
			if (z[i] == k) {
				z.splice(i, 1);
			}
		}

		this.refresh();
	},

	main: function (k) {
		var id = "contact" + k;
		var contact = $("#" + id).clone();

		contact.attr("id", "contact");
		contact.insertAfter("#info_add");

		for (var i = 0; i < z.length; i++) {
			if (z[i] == k) {
				z.splice(i, 1);
				z.splice(0, 0, k);
			}
		}

		$("#" + id).remove();
		contact.attr("id", id);

		this.refresh();
	},

	refresh: function () {
		for (var i = 0; i < z.length; i++) {
			var k = i + 1;
			var legend = "#contact" + z[i] + " legend";
			var action = "#action" + z[i];

			if (i == 0) {
				$(legend).html("主联系人 1");
				$(action).html("");
				$(action).parent("tr").hide();
			} else {				
				$(legend).html("<a href=\"javascript:void(0)\" onclick=\"Contact.remove(" + z[i] + ")\">x</a> 联系人 " + k);
				$(action).html("<a href=\"javascript:void(0)\" onclick=\"Contact.main(" + z[i] + ")\">设为主联系人</a>");
				$(action).parent("tr").show();
			}
		}
	}
}
